const http = require('http');
const fs = require('fs');
const path = require('path');
const { constants } = require('buffer');

var filePath = process.argv[2];
var dirPath = __dirname;

http.createServer((req,res)=>{
    res.writeHead(200,{"Content-Type": "text/html"});
    if(filePath){
        fs.access(path.join(dirPath, filePath), constants.F_OK, (err)=>{
            if(err){
                console.log(err);
            }else{
                fs.open(path.join(dirPath, filePath), (err, data)=>{
                    if(err){
                        console.log(err);
                    }else{
                        fs.read(data, (err, bytesRead, buffer)=>{
                            var text = buffer.toString();
                            res.write("<!DOCTYPE html><html>" + 
                            "<head></head><body>"+
                            "<div>"+ text +"</div></body></html>");
                            res.end();
                        })
                    }
                })
            }
        })
    }else{
        fs.open(path.join(dirPath, '/fileReader2.js'), (err, data)=>{
            if(err){
                console.log(err);
            }else{
                fs.read(data, (err, bytesRead, buffer)=>{
                    var text = buffer.toString();
                    res.write("<!DOCTYPE html><html>" + 
                    "<head></head><body>"+
                    "<div>"+ text +"</div></body></html>");
                    res.end();
                })
            }
        })
    }
}).listen(8081);